package com.acargil.sudoku.view.listeners;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;

import com.acargil.sudoku.model.ISudokuEngine;
import com.acargil.sudoku.model.util.ISudokuUtil;
import com.acargil.sudoku.model.util.SudokuUtilFactory;
import com.acargil.sudoku.view.ISudokuView;
import com.acargil.sudoku.view.util.MessageFactory;

public class SaveListener implements ActionListener {
	
	private static ActionListener instance = null; 
	private ISudokuEngine model;
	private ISudokuView view;
	private ISudokuUtil util;
	
	public static ActionListener getInstance(ISudokuEngine model, ISudokuView view) {
		if (instance == null) {
			instance = new SaveListener(model, view);
		}
		
		return instance;
	}
	
	protected SaveListener(ISudokuEngine model, ISudokuView view) {
		this.model = model;
		this.view = view;
		this.util = SudokuUtilFactory.createSudokuUtil();
	}
	
	@Override
	public void actionPerformed(ActionEvent e) {
		boolean result = false;
		try {
			File file = this.view.getSaveFile();
			if (file != null) {
				result = this.util.save(this.model, new FileOutputStream(file));
				if (result) {
					MessageFactory.informationMessage("Game is successfully saved!");
				}
			}
		} catch (FileNotFoundException ex) {
			MessageFactory.errorMessage("Game cannot be saved!");
		} catch (Exception ex) {
			MessageFactory.errorMessage("Game cannot be saved!");
		}
	}
}